<template>
  <div class="background-container">
    <div class="navigation" >
      <!-- Navbar -->
      <nav>
        <div id="navbarNav">
          <!--              左侧-->
          <ul class="nav-menu">
            <!--                <img src="@/assets/logo2.png" alt="Logo" class="logo">-->
            <li>
              <span class="title">首页</span>
            </li>
            <li class="nav-item">
              <router-link to="/PersonView" class="nav-link"
              ><van-icon name="contact-o" />个人中心
              </router-link
              >
            </li>
            <li class="nav-item">
              <router-link to="/Course-index" class="nav-link"
              ><van-icon name="video-o" />课程管理
              </router-link>
            </li>
            <li class="nav-item">
              <router-link to="/about" class="nav-link"
              ><van-icon name="friends-o" />关于我们
              </router-link
              >
            </li>
            <li class="nav-item">
              <router-link to="/LinkUS" class="nav-link"
              ><van-icon name="chat-o" />联系客服
              </router-link
              >
            </li>
          </ul>
          <!--              中间-->
          <form class="search" @submit.prevent="submitForm">
      <input v-model="searchQuery" placeholder="搜索课程或教师" aria-label="Search" class="searchFont" />
      <el-select v-model="searchType" placeholder="请选择搜索类型" class="searchSelect">
        <el-option label="搜索课程" value="course"></el-option>
        <el-option label="搜索教师" value="teacher"></el-option>
      </el-select>
      <el-button @click="submitForm" type="submit" icon="el-icon-search" class="searchButton"></el-button>
    </form>
          <div class="nav-button-container">
            <van-button
                icon="https://fastly.jsdelivr.net/npm/@vant/assets/user-active.png"
                type=""
                size="mid"
                class="nav-button"
                @click="logout"
            >
              退出登录
            </van-button>
          </div>
        </div>

      </nav>
    </div>

    <br>

    <!-- Content -->
    <div class="g-container">  
  <div class="carousel-wrapper"> 
    <el-carousel :interval="4000" type="card" height="300px" style="width: 100%; overflow: hidden;margin-top: 12px">  
      <el-carousel-item v-for="(video, id) in videos.slice(0, 3)" :key="id" style="width: 390px;margin-left: 200px;">  
        <a @click="goToVideoDetail(videos, id)" style="display: block; width: 100%; ">  
          <img :src="video.course_logo || 'default-cover.jpg'" style="height: 225px; object-fit: cover; width: 100%;">  
          <div class="overlay">  
            <i class="el-icon-video-play">{{ video.playNumber }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</i>
          <i class="el-icon-star-on">{{ video.favoriteNumber }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</i>
          <i class="el-icon-chat-dot-round">{{ video.commentNumber }}</i>
          </div>  
          <p style="margin-top: 5px; text-align: left;">{{ video.course_name }}</p>  
        </a>  
        <a @click="goTeacher(video.id)">  
          <div class="upzhu">  
            <img src="@/assets/upzhu.png" alt="Logo" class="img">  
            <p>教师:{{ video.lecturerName }}</p>  
          </div>  
        </a>  
      </el-carousel-item>  
    </el-carousel>  
  </div>  
</div>    

    <h2>推荐课程：</h2><br>
    <div class="course" style="display: flex; flex-wrap: wrap; justify-content: center; gap: 40px;">
      <div v-for="(video, id) in videos" :key="id"
      v-show="id >= 3"  
           style="margin-bottom: 10px;">
        
        <a @click="goToVideoDetail(videos,id)" style="display: block; width: 260px;">
          <img :src="video.course_logo || 'default-cover.jpg'"
               style="width: 100%; height: 150px; object-fit: cover; border-radius: 10px;">
        <div class="overlay">
         
          <i class="el-icon-video-play">{{ video.playNumber }}&nbsp;&nbsp;&nbsp;&nbsp;</i>
          <i class="el-icon-star-on">{{ video.favoriteNumber }}&nbsp;&nbsp;&nbsp;&nbsp;</i>
          <i class="el-icon-chat-dot-round">{{ video.commentNumber }}</i>
        </div>
          <p style="margin-top: 5px; text-align: left;margin-left: 0px;">{{ video.course_name }}</p>
         
        </a>
        <a @click="goTeacher(video.id)">
          <div class="upzhu">
           
            <img src="@/assets/upzhu.png" alt="Logo" class="img">
           
            <p>教师:{{ video.lecturerName }}</p>
          </div>

        </a>
      </div>
    </div>


    <!-- Footer -->
    <footer class="bg-dark text-white text-center py-4 mt-5">
      <p>&copy; GiliGili在线教育平台. All Rights Reserved.</p>
    </footer>
  </div>
</template>


<script>
import Swiper from "swiper";
import axios from "axios";
import "swiper/css/swiper.min.css"; // 引入Swiper的CSS样式


export default {
  data() {
    return {
      searchQuery: '',
      searchType: 'course',
      isFavorites: [],
      videos: [],
      favorites: [],
      courses: [],
      swiper: null,
      username: "",
      checked: true,
      swiperList: [
        {
          id: 1,
          title: "1",
          imgUrl: require("@/assets/logo2.png"),
        },
        {
          id: 2,
          title: "2",
          imgUrl: require("@/assets/444.jpg"),
        },
        {
          id: 3,
          title: "3",
          imgUrl: require("@/assets/333.png"),
        },
        {
          id: 4,
          title: "4",
          imgUrl: require("@/assets/222.jpg"),
        },
        {
          id: 5,
          title: "5",
          imgUrl: require("@/assets/555.jpg"),
        },
      ],
    };
  },
  mounted() {
    this.initSwiper();
    // 加载时从 localStorage 检查收藏状态
    const favorites = JSON.parse(localStorage.getItem('favorites')) || [];
    this.isFavorite = favorites.includes(this.index);
  },
  beforeDestroy() {
    // 销毁 swiper 实例以避免内存泄漏
    if (this.swiper && this.swiper.destroy) {
      this.swiper.destroy(true, true);
    }
  },
  created() {
    this.fetchVideos();
  },
  methods: {

    submitForm() {
      if(this.searchType==="course"){
        axios.post('http://localhost:8081/springboot01/course/searchCourse',
          {
            search: this.searchQuery
          },
          {
            headers: {
              'Content-Type': 'application/json'
            }
          }
      )
          .then(response => {
            console.log('Response data:', response.data);
            if (response.data.msg === "请求成功!") {
              this.searchQuery = ''
              localStorage.setItem("courses", JSON.stringify(response.data.data))
              this.$router.push('/CourseSearch');

            } else {
              alert(response.data.msg)
            }
          })
          .catch(error => {
            console.error('搜索失败', error);
            this.error = '请重新搜索';
          });
      }else{
        axios.post('http://localhost:8081/springboot01/user/listCourseUser',
          {
            search: this.searchQuery
          },
          {
            headers: {
              'Content-Type': 'application/json'
            }
          }
      )
          .then(response => {
            console.log('Response data:', response.data);
            if (response.data.msg === "请求成功!") {
              this.searchQuery = ''
              localStorage.setItem("courses", JSON.stringify(response.data.data))
              this.$router.push('/CourseSearch');

            } else {
              alert(response.data.msg)
            }
          })
          .catch(error => {
            console.error('搜索失败', error);
            this.error = '请重新搜索';
          });
      }
      
    },
    goToVideoDetail(videos, id) {
      this.$router.push(`/videoDetail?videos=${encodeURIComponent(JSON.stringify(videos[id]))}`);

    },
    goTeacher(id) {
  this.$router.push({
    name: 'UpView', 
    params: { Id: id }
  });
},
    logout() {
      // 这里可能还需要处理清除登录状态的操作
      this.$router.push("/");
    },

    initSwiper() {
      this.swiper = new Swiper(".swiper-container", {
        loop: true,
        autoplay: {
          delay: 3000,
          disableOnInteraction: false,
        },
        pagination: {
          el: ".swiper-pagination",
          clickable: true,
        },
        navigation: {
          nextEl: ".swiper-button-next",
          prevEl: ".swiper-button-prev",
        },
        slidesPerView: 1,
        spaceBetween: 30,
        observer: true,
        observeParents: true,
      });
    },
    async fetchVideos() {
      try {
        const response = await axios.get('http://localhost:8081/springboot01/course/geturl');
        const backData = response.data;
        this.videos = backData.map(item => ({
          id: item.id,
          url: item.url,
          course_name: item.courseName,
          course_logo: item.courseLogo,
          lecturerName: item.lecturerName,
          playNumber:item.playNumber,
          commentNumber:item.commentNumber,
          favoriteNumber:item.favoriteNumber,
          username:item.username,
          courseName:item.courseName,
          introduce:item.introduce,


        }));
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    },
    
  },

};
</script>

<style scoped>

.el-carousel__item h3 {
    color: #475669;
    font-size: 14px;
    opacity: 0.75;
    line-height: 200px;
    margin: 0;
  }
  
  .el-carousel__item:nth-child(2n) {
    background-color: #90c2fc;
  }
  
  .el-carousel__item:nth-child(2n+1) {
    background-color: #90c2fc;
  }

.navigation {
  align-content: center;
  height: 120px;
}
h3{
  margin-left: -1200px;
}

.background-container {
  background-image: url('/src/assets/fengmian3.jpg');
  background-size: cover; /* 背景图大小，cover 表示尽可能填充容器 */
  background-position: top; /* 背景图位置，顶部对齐 */
  background-repeat: no-repeat; /* 背景图不重复 */
  height: 150px; /* 设置容器高度，可以根据实际需求调整 */
  /* 其他样式 */
  align-content: center;
}

video {
  height: 300px;
  width: 300px;
}


.title {
  /* 标题样式 */
  font-size: 30px;
  font-weight: bold;
  margin-right: 30px;
  color: #96ccde;
}

ul {
 padding: 0;
 margin-bottom: 10px;
  list-style-type: none;
 margin: 0 auto;
}

li {
font-size: large;
 display: inline-block;
  list-style: none;
  margin-right: 10px;
}


.search {
  display: inline-block;
  font-size: 18px;
  margin-right: 100px;
  margin-left: 200px;
  opacity: 0.8;
}


.searchFont {
  width: 200px; /* 可以设置为具体的像素值或者百分比 */
  padding: 12px; /* 增加内边距使文本框更大 */
  font-size: 18px; /* 可选，增大字体大小 */
  border: 1px solid #ccc; /* 可选，保持边框样式 */
  height: 40px;
  /*border-radius: 8px; !* 可选，增加圆角效果 *!*/

}
.searchSelect{
  width: 110px;
  height: 20px;
}

.searchButton {
  width: 80px;
  height: 40px;
  border-radius: 0; /* 可选，增加圆角效果 */
}

.logo {
  width: 100px;
  height: auto;
}

.swiper-container {
  display: flex;
  /*width: 100%;*/
  width: 600px;
  height: 400px;
  /*margin-left: 0;*/
  justify-content: center;
  margin-left: auto;
  margin-right: auto;
  border-radius: 10px;

}


.swiper-slide {
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center; 
}

.swiper-slide-image {
  display: block; /* 防止图片底部有间隙 */
  margin: 0 auto; /* 水平居中图片 */
  width: 105%;
  height: 400px;
  border-radius: 20px;

}
#navbarNav {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.nav-menu {
  list-style: none;
  padding: 0;
  display: flex;
  margin-left: 50px;
  width: 600px;
}


.nav-item {
/*  margin-right: 30px; !* 或者使用其他合适的间距 *!*/
  font-size: 18px;
  /* 添加边框样式 */
  border: 1px solid #ccc; /* 这里可以根据需要更改边框的颜色和宽度 */
  padding: 5px 10px; /* 添加内边距，让内容不会紧贴边框 */
}

.nav-item:hover {
  background-color: #c2e0f1; /* 鼠标悬停时的背景颜色 */
  border-color: #c2e0f1; /* 鼠标悬停时的边框颜色 */
}

.nav-item
.nav-link {
  color: #ffcfcf;
  text-decoration: none; /* 取消链接的下划线 */
}

.course {
  display: inline-block;
  align-content: center;
}

.nav-button-container {
  /* 用于放置退出登录按钮 */
  margin-right: 50px;

  height: auto;
  opacity: 0.7;
}

.nav-button {
  width: 120px;
}

h2 {
  margin-left: 100px;
}


.upzhu {
  font-size: 15px;
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.upzhu p {
  font-style: italic;
  font-size: 13px;
  text-align: center;
  /*margin-top: 10px;*/
  color: #828282;


}

.img {
  width: 20px;
  height: auto;
  margin-right: 5px;
  margin-left: 0px;
  display: block;
}


.g-container {  
  display: flex; /* 启用Flexbox */  
  justify-content: center; /* 水平居中 */  
  width: 100%; /* 容器宽度 */  
}  
  
.carousel-wrapper {  
  max-width: calc(4 * 390px); /* 假设最多显示3个走马灯项，每个390px宽 */  
  /* 宽度保持为100%，但max-width会限制其最大宽度 */  
  width: 100%;  
  padding: 0 20px; /* 如果你想在走马灯两侧添加一些内边距 */  
  box-sizing: border-box; /* 防止内边距影响总宽度 */ 
}

.searchSelect{
  width: 110px;
  height: 20px;
}

</style>